<template>
  <div id="login">

    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
      <el-form :model="loginForm" :rules="rules" class="login-container" size="medium" @keydown.enter="handleClick">
        <h3 class="login_title">用户注册</h3>
        <el-form-item prop="username">
          <el-input type="text" v-model="loginForm.username" autofocus ref="username" auto-complete="off"
            placeholder="用户名" spellcheck="false">
          </el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <el-input type="text" v-model="loginForm.phone" autofocus ref="phone" auto-complete="off" placeholder="电话"
            v-on:input="change">
          </el-input>
        </el-form-item>
        <el-form-item prop="email">
          <el-input type="text" v-model="loginForm.email" autofocus ref="email" auto-complete="off" placeholder="邮箱"
            v-on:input="change">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" autofocus ref="password" auto-complete="off"
            placeholder="密码" v-on:input="change">
          </el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input type="password" v-model="loginForm.repassword" autofocus ref="repassword" auto-complete="off"
            placeholder="确认密码" v-on:input="change">
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="loginForm.code" placeholder="验证码" clearable>
            <template #append>
              <el-button style="color: blue;float: right" :disabled="disabled" @click="getCode">
                {{ btnTxt }}
              </el-button>
            </template>

          </el-input>
        </el-form-item>
        <el-form-item style="width: 100%;">
          <el-checkbox class="login_remember" v-model="checked">
            <span style="color: #409EFF">记住我</span>
            <label style="color: #949493;text-align: right;">不是自己电脑请勿勾选</label>
          </el-checkbox>
        </el-form-item>


        <el-form-item style="width: 100%">
          <el-button type="primary" class="button_login" @click="toLoginPage">去登录</el-button>
          <el-button type="primary" class="button_register" @click="onSignUpClick">注册</el-button>

        </el-form-item>
      </el-form>
    </el-col>
    <p class="login-copyright">© {{ currentYear }} cf 版权所有</p>
  </div>
</template>

<script>
import { postRequestWithRaw, getRequest, postRequest } from "../api/axiosRequest";
export default {
  name: 'signUp',
  data() {
    let validatePhone = (rule, value, callback) => {
      /*console.log(rule);
      console.log(value);
      console.log(callback);*/
      if (!value) {
        callback(new Error('手机号不能为空'));
      }
      //使用正则表达式进行验证手机号码
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error('手机号不正确'));
      }
      //自定义校验规则 需要调用callback()函数！
      callback();
    };
    let validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('邮箱不能为空'));
      }
      // 使用正则表达式进行验证邮箱地址
      if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(value)) {
        callback(new Error('邮箱地址不正确'));
      }
      // 自定义校验规则 需要调用callback()函数！
      callback();
    }
    return {
      isVerificationShow: false,
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        repassword: [{ required: true, message: '确认密码不能为空', trigger: 'blur' }]
      },
      checked: true,
      loginForm: {
        username: '',
        phone: '',
        email: '',
        password: '',
        repassword: '',
        code: '',
      },
      msg: null,
      currentRole: 1, // 初始状态为空
      isInput: false,
      isValid: false,
      currentYear: new Date().getFullYear(),

      //验证码部分所需的数据
      btnTxt: "获取验证码",
      disabled: false,
      time: 0,
    }
  },
  methods: {
    //获取手机验证码方法
    async getCode() {
      if (!this.loginForm.username) {
        //手机号校验不通过
        ElMessage({
          message: '请输入用户名！',
          type: 'warning',
        })
        //1.校验手机号码
      } else if (!this.loginForm.phone) {t
        //手机号校验不通过
        ElMessage({
          message: '请输入手机号码！',
          type: 'warning',
        })
      } else if (!this.loginForm.email) {
        //手机号校验不通过
        ElMessage({
          message: '请输入邮箱！',
          type: 'warning',
        })
      } else if (!this.loginForm.password) {
        //密码校验不通过
        ElMessage({
          message: '请输入密码！',
          type: 'warning',
        })
      } else if (!this.loginForm.repassword) {
        //密码校验不通过
        ElMessage({
          message: '请输入确认密码！',
          type: 'warning',
        })
      } else if (!/^1[3456789]\d{9}$/.test(this.loginForm.phone)) {
        //此处失去焦点后自动触发校验手机号规则
      } else {
        //2.【手机号码校验通过】发送axios请求 获取验证码
        this.time = 30;   //设置倒计时的时间（单位：秒）
        this.disabled = true;
        this.timer();     //调用倒计时方法
        const result = await getRequest('/send/' + this.loginForm.phone);
        console.log(result);
        //shuqiyue121
        //15390197897
        //2594359181@qq.com
        if (result.status === 200) {
          if (result.data.status === 1) {
            //短信验证码发送成功时的消息提示
            ElMessage({
              message: result.data.msg,
              type: 'success',
            })
          } else if (result.data.status === 0) {
            //短信验证码发送失败时的消息提示
            ElMessage({
              message: result.data.msg,
              type: 'warning',
            })
          }
        }
      }
    },
    //倒计时方法
    timer() {
      if (this.time > 0) {
        this.time--;
        console.log(this.time);
        this.btnTxt = this.time + "s后重新获取验证码";
        setTimeout(this.timer, 1000);
      } else {
        this.time = 0;
        this.btnTxt = "获取验证码";
        this.disabled = false;
      }
    },
    // 跳转到登录页
    toLoginPage() {
      this.$router.push('/login')
    },
    // 注册，待完成
    async onSignUpClick() {
      try {
        //post请求，表单
        const result = await postRequest("/user/checkUsername", {
          username: this.loginForm.username
        });
        console.log(result);
        if (result.status === 200) {
          const data = result.data;
          if (data.status === 0) {
            this.msg = data.msg
            ElNotification({
              title: '注册提示',
              message: this.msg,
              type: 'warning',
              duration: 3000, // 显示 3 秒后自动关闭
            });
            return
          }

          // 获取表单数据
          const form = this.loginForm;
          const keys = Object.keys(form);
          console.log("form:" + form);
          console.log("keys:" + keys);

          // let isValid = true;
          // 遍历表单，如果其中一个为空，则将isValid设为false
          keys.forEach(key => {
            if (!form[key] || data.status === 0) {
              this.isValid = false;
            } else if (form[key] && data.status === 1) {
              this.isValid = true;
            }
          });

          console.log(this.isValid);

          // if (data.status === 1) {
          //   this.isValid = true
          // } else {
          //   this.isValid = false
          // }
        } else {
          ElNotification({
            title: '注册提示',
            message: this.msg,
            type: 'warning',
            duration: 3000, // 显示 3 秒后自动关闭
          });
          return;
        }
      } catch (error) {
        console.log(error);


      } finally {
        console.log("finally");
      }
      if (this.isValid) {
        try {
          //post请求json
          const result = await postRequestWithRaw("/user/signUp", {
            username: this.loginForm.username,
            phone: this.loginForm.phone,
            email: this.loginForm.email,
            password: this.loginForm.password,
            verificationCode: this.loginForm.code,
            role: this.currentRole
          });
          if (result.status === 200) {
            const data = result.data;
            if (data.status === 1) {
              this.msg = data.msg
              ElNotification({
                title: '注册提示',
                message: this.msg,
                type: 'success',
              });
              // 注册完了之后，将页面跳转到登录页
              this.$router.push("login")
            } else {
              this.msg = data.msg
              ElNotification({
                title: '注册提示',
                message: this.msg,
                type: 'warning',
              });
            }
          } else {
            console.log("NetWork Error");
          }
        } catch (error) {
          console.log(error);
        } finally {
          console.log("finally");
        }
      } else {
        ElNotification({
          title: '注册提示',
          message: '请完成表单输入',
          type: 'warning',
          duration: 3000,
        });
      }
    }

  },
  change() {
    // 如果监听到输入框发生变化，那么采用用户输入的密码
    this.isInput = true;
  },
}
</script>

<style scoped>
#login {
  background-image: url('/src/assets/image/signUpPage/starSky.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
  position: fixed;
}

.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 40px auto;
  width: 30%;
  padding: 25px 30px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  opacity: 0.7;

  /* 媒体查询，根据屏幕宽度改变样式 */
  @media screen and (max-width: 1200px) {
    width: 70%;
    margin: 40px auto;
  }

  /* 媒体查询，根据屏幕宽度改变样式 */
  @media screen and (max-width: 768px) {
    width: 70%;
    margin: 40px auto;
  }

  @media screen and (max-width: 480px) {
    width: 70%;
    margin: 40px auto;

  }
}

.selected-role {
  background-color: #409EFF;
  color: white;
}

.login_title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}

.login_remember {
  margin: 0px;
  text-align: left;
  float: left;

}

.button_login {
  width: 40%;
  background: #409EFF;
  border: none;
  float: left
}

.button_register {
  width: 40%;
  background: #505458;
  border: none;
  float: right;
}

.login-copyright {
  color: #fcfdfd;
  padding-bottom: 20px;
  text-align: center;
  position: relative;
  z-index: 1;
}

@media screen and (min-height: 550px) {
  .login-copyright {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
  }
}
</style>